from django.db import models
from django.contrib.auth.models import AbstractUser
from itsdangerous import TimedJSONWebSignatureSerializer as JWSSerializer, BadData
from django.conf import settings
# Create your models here.
from users import constants
from meiduo_mall.utils.models import BaseModel


class User(AbstractUser):
    """用户模型类"""
    mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
    # 用户模型类中继承的AbstractUser默认是有email字段的，默认状态是False
    # 这里需要补充的是判断用户的邮箱是否激活
    # 从用户发送过来的邮箱，不一定是准确有效的，我们会发送确认链接给用户
    # 用户在点击链接之后才将这个字段设置为True　所以此字段是布尔类型
    email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态')
    # 修改模型类之后要做迁移操作
    # 设置默认地址在用户模型中，一个用户只有一个默认地址
    default_address = models.ForeignKey('Address', related_name='users', null=True, blank=True,
                                        on_delete=models.SET_NULL, verbose_name='默认地址')

    class Meta:
        db_table = 'tb_users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    # 像实现cerate_user方法一样，我们给对象新增可以调用的方法
    def generate_verify_email_url(self):
        """
        生成验证邮箱的url
        """
        # 为了确认是哪位用户要激活，我们在返回的链接中需要加上user_id　和其他信息，比如email
        # 为了不让用户可以修改user_id，我们进行加密处理
        serializer = JWSSerializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
        data = {'user_id': self.id, 'email': self.email}
        token = serializer.dumps(data).decode()
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token
        return verify_url

    @staticmethod
    def check_verify_email_token(token):
        """
        :param token: 用来校验传入的传入的token是否有效
        :return:
        """
        serializer = JWSSerializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
        try:
            data = serializer.loads(token)
        except BadData:
            return None
        else:
            id = data.get('user_id')
            email = data.get('email')
            try:
                user = User.objects.get(id=id, email=email)
            except User.DoesNotExist:
                return None
            else:
                return user


class Address(BaseModel):
    """
    用户地址   继承BaseModel　添加创建时间和更新时间字段
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='addresses', verbose_name='用户')
    title = models.CharField(max_length=20, verbose_name='地址名称')
    receiver = models.CharField(max_length=20, verbose_name='收货人')
    province = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='province_addresses', verbose_name='省')
    city = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='city_addresses', verbose_name='市')
    district = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='district_addresses', verbose_name='区')
    place = models.CharField(max_length=50, verbose_name='地址')
    mobile = models.CharField(max_length=11, verbose_name='手机')
    tel = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name='固定电话')
    email = models.CharField(max_length=30, null=True, blank=True, default='', verbose_name='电子邮箱')
    is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'tb_address'
        verbose_name = '用户地址'
        verbose_name_plural = verbose_name
        ordering = ['-update_time']    # 以用户更新的时间进行地址排序

